//
//  ZHLEEPopBtnView.swift
//  ZHLEEBlog_swift_pro
//
//  Created by ZHLEEBlander on 15/10/13.
//  Copyright © 2015年 ZHLEEBlander. All rights reserved.
//

import UIKit

class ZHLEEPopBtnView: UIButton {
    
    var imageBack: UIImageView?
    
    var block:(()->())?

    init(customView:UIView){
    
        super.init(frame: CGRectMake(0, 0, ScreenW, ScreenH))
        addTarget(self, action: "converButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        setupView(customView)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupView(customView:UIView){
    
        let image = UIImage(named: "popover_background")
        let imageBack = UIImageView(image: image?.stretchableImageWithLeftCapWidth(Int((image!.size.width) * 0.5), topCapHeight: Int(image!.size.height * 0.5)))
        
        imageBack.size = CGSizeMake(customView.width + 10, customView.height + 22)
        
        self.addSubview(imageBack)
        self.imageBack = imageBack
        
        //添加customView
        customView.x = 5
        customView.y = 13
        
        imageBack.addSubview(customView)
    
    }
    
    func show(targetButton:UIButton){
    
        /// convertRect
        let rect = targetButton.convertRect(targetButton.bounds, toView: nil)
//        let rect = targetButton.superview!.convertRect(targetButton.frame, toView: nil)
        self.imageBack?.centerX = targetButton.centerX
        self.imageBack?.y = CGRectGetMaxY(rect)
        //获取窗口
        let window = UIApplication.sharedApplication().windows.last
        
        window?.addSubview(self)
    }
    
    @objc private func converButtonClick(button:UIButton){
    
        if let blo = block{
        
            blo()
        }
        button.removeFromSuperview()
        
    }
}
